var express = require('express');
var router = express.Router();
const http = require('superagent');

const OAUTH_URL = 'https://www.facebook.com/v2.10/dialog/oauth?client_id=@APP_ID&redirect_uri=@REDIRECT_URI&state=@STATE&response_type=code&scope=email';
const APP_ID = '485527178491031';
const APP_SECRET = '525a5da772931644ebfa40d7ec440439';
const SYSTEM_URL = 'http://www.xrian.com/users/facebook';

const GET_CODE_URL = 'https://graph.facebook.com/v2.10/oauth/access_token?client_id=@APP_ID&redirect_uri=@REDIRECT_URI&client_secret=@APP_SECRET&code=@CODE_PARAMETER';

const VALID_URL = 'https://graph.facebook.com/debug_token?input_token=@TOKEN_TO_INSPECT&access_token=@APP_TOKEN_OR_ADMIN_TOKEN';

const asda = '/oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials';

/* GET users listing. */
router.get('/facebook', function(req, res, next) {
  let code = req.query.code;
  if(code){
    let session = req.session.state;
    console.log('session 中的:', session);
    let state = req.query.state;
    console.log('请求参数的:', state);
    console.log('返回的 code:', code);
    let url = GET_CODE_URL.replace('@APP_ID', APP_ID).replace('@REDIRECT_URI', SYSTEM_URL).replace('@APP_SECRET', APP_SECRET).replace('@CODE_PARAMETER', code);
    http.get(url)
      .type('json')
      .accept('json')
      .end(function (err, response) {
        if(err){
          console.log('回调报错', err);
          res.status(response.status).send(response.body);

        }else{
          var user = response.body;
          console.log('通过 code 返回的信息');
          console.log(response.text);
          let url = VALID_URL.replace('@APP_TOKEN_OR_ADMIN_TOKEN', APP_ID+'|'+APP_SECRET).replace('@TOKEN_TO_INSPECT', user.access_token);
          http.get(url)
            .type('json')
            .accept('json')
            .end(function (err, response) {
              console.log('校验用户信息结束');
              if(err){
                console.log('回调报错', err);
                res.status(response.status).send(response.body);
              }else{
                // 如果顺利进入到这里,可以获取到用户的唯一标识 response.body.user_id
                console.log(response.body);
                http.get('https://graph.facebook.com/v2.10/'+response.body.data.user_id+'?fields=id,cover,email,name,first_name,last_name,age_range,link,gender,locale,picture,timezone,updated_time,verified&access_token='+APP_ID+'|'+APP_SECRET)
                    .type('json')
                    .accept('json')
                    .end(function (err, response) {
                      if(err){
                        console.log('报错了:', err);
                        res.status(response.status).send(response.body);
                      }else{
                        console.log('获取用户信息成功:', response.statusCode);
                        console.log(response.body);
                        res.status(response.status).send(response.body);

                      }
                    });
              }
            })


        }

    })


  }else{
    let timeStamp = new Date().getTime()+'';
    req.session.state = timeStamp;
    let url = OAUTH_URL.replace('@APP_ID', APP_ID).replace('@REDIRECT_URI', SYSTEM_URL).replace('@STATE', timeStamp);
    res.redirect(url);
  }
});

module.exports = router;
